let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let Goods = require('../modules/goods');

//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/mail');

mongoose.connection.on('connected', function () {
    console.log('connected');
});

mongoose.connection.on('error', function () {
    console.log('连接失败');
});

mongoose.connection.on('disconnected', function () {
    console.log('disconnected');
});


router.get('/', function (req, res, next) {

    /*获取get参数*/
    let sort = req.param('sort');  //排序方式
    let page = parseInt(req.param('page'));  //页数
    let pageSize = parseInt(req.param('pageSize'));  //每页条数

    /*计算skip */
    let skip = (page - 1) * pageSize;

    let params = {};
    let goodsModel = Goods.find(params).skip(skip).limit(pageSize);

    goodsModel.sort({'salePrice': sort});
    goodsModel.exec(function (err, doc) {
        if (err) {
            res.json({
                status: 0,
                msg: err.message
            });
        } else {
            res.json({
                status: 0,
                msg: '',
                result: doc
            });
        }

    });

});

module.exports = router;
